package com.example.music.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.example.music.R
import com.example.music.model.Song

class SongAdapter : RecyclerView.Adapter<SongAdapter.SongViewHolder>() {
    private var songs: List<Song> = emptyList()
    private var onItemClickListener: ((Song, Int, List<Song>) -> Unit)? = null

    fun submitList(newList: List<Song>) {
        songs = newList
        notifyDataSetChanged()
    }

    fun setOnItemClickListener(listener: (Song, Int, List<Song>) -> Unit) {
        onItemClickListener = listener
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SongViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.item_song, parent, false)
        return SongViewHolder(view)
    }

    override fun onBindViewHolder(holder: SongViewHolder, position: Int) {
        holder.bind(songs[position]) {
            onItemClickListener?.invoke(it, position, songs)
        }
    }

    override fun getItemCount() = songs.size

    class SongViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        private val coverImage: ImageView = itemView.findViewById(R.id.songCover)
        private val titleText: TextView = itemView.findViewById(R.id.songTitle)
        private val artistText: TextView = itemView.findViewById(R.id.songArtist)

        fun bind(song: Song, onClick: (Song) -> Unit) {
            titleText.text = song.name
            song.artist?.let {
                artistText.visibility = View.VISIBLE
                artistText.text = it
            } ?: run {
                artistText.visibility = View.GONE
            }
            
            song.coverUrl?.let { url ->
                Glide.with(itemView.context)
                    .load(url)
                    .error(R.drawable.ic_error_placeholder)
                    .into(coverImage)
            }

            itemView.setOnClickListener {
                onClick(song)
            }
        }
    }
} 